// service.ts
import axios from 'axios'
import type { AxiosInstance, AxiosResponse } from 'axios'
import { config } from './config'
import { errorMessage } from './status'
import { ElMessage } from 'element-plus'

const PATH_URL = ''

// 创建axios实例
const service: AxiosInstance = axios.create({
  baseURL: PATH_URL,
  timeout: config.requestTimeout,
})

// 请求拦截器
service.interceptors.request.use(
  (config: import('axios').InternalAxiosRequestConfig) => {
    // 添加token
    const token = window.sessionStorage.getItem('token')
    if (token) {
      config.headers['X-Access-Token'] = token
    }

    // 处理get请求参数编码
    if (config.method === 'get' && config.params) {
      let url = config.url || ''
      url += '?'
      const keys = Object.keys(config.params)
      for (const key of keys) {
        const value = config.params[key]
        if (value !== undefined && value !== null) {
          url += `${key}=${encodeURIComponent(value)}&`
        }
      }
      url = url.slice(0, -1)
      config.params = {}
      config.url = url
    }

    return config
  },
  (error) => {
    console.error('Request Error:', error)
    return Promise.reject(error)
  },
)

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.config.responseType === 'blob') {
      return response
    }
    // const { data } = response
    // if (data?.status != 'success') {
    //   ElMessage({
    //     message: data?.msg ? data.msg : '系统错误',
    //     type: 'error',
    //   })
    // }
    // 错误提示由业务层处理
    return response.data
  },
  (error) => {
    console.error('Response Error:', error)
    const status = error?.response?.status
    const msg = status ? errorMessage(status) : 'Network Error'
    return Promise.reject({ message: msg, ...error })
  },
)

export { service }
